<template>
  <div class="addEditArticlePageCont">
    <!-- <div class="title">当前位置：案场海报 / {{ title }}</div> -->

    <div class="addEditArticlePageMian">
      <div class="allBox">
        <div class="tempPe">
          <div class="tit">
            模板预览
            <span v-if="editorInfo.dragInfo.copyWriting.length">可以自由拖动文案的位置</span>
          </div>
          <div class="placardTemBox">
            <div class="placardBox">
              <div class="placardTem" ref="placardTem">
                <div
                  class="hasUrl"
                  ref="hasUrl"
                  :style="{
                    width: '375px',
                    height: imageHeight + 'px',
                    position: 'relative',
                    overflow: 'hidden'
                  }"
                  v-if="editorInfo.fileList[0]?.url">
                  <!--  文案 -->
                  <vue-draggable-resizable
                    style="cursor: pointer"
                    v-if="lateFlag"
                    v-for="(item, index) in editorInfo.dragInfo.copyWriting"
                    :key="index"
                    :x="item.coordinateX ? item.coordinateX : 0"
                    :y="item.coordinateY ? item.coordinateY : 50 * index"
                    w="auto"
                    h="auto"
                    :resizable="false"
                    @dragging="
                      (x, y) => {
                        onDrag(x, y, item)
                      }
                    "
                    :parent="true">
                    <p v-html="item.content" ref="pText" class="pText"></p>
                  </vue-draggable-resizable>
                  <!-- 二维码 -->
                  <vue-draggable-resizable
                    v-if="activeImgIndex == 2 && hiddenFlag && editorInfo.fileList[0]?.url && lateFlag"
                    :x="editorInfo.qrCode.coordinateX"
                    :y="editorInfo.qrCode.coordinateY"
                    :w="editorInfo.qrCode.width"
                    :h="editorInfo.qrCode.height"
                    :lock-aspect-ratio="true"
                    @dragging="onDragEr"
                    :resizable="true"
                    :minw="10"
                    :minh="10"
                    :maxw="100"
                    :maxh="100"
                    @resizing="onResize"
                    :parent="true">
                    <Tooltip
                      content="可自由调整二维码位置"
                      placement="top"
                      :transfer="true"
                      max-width="100"
                      :disabled="alwaysFlag"
                      :always="!alwaysFlag">
                      <template #content>
                        <p class="toolName">可自由调整二维码位置</p>
                      </template>
                      <img
                        style="display: block; width: 100%; height: 100%"
                        src="https://static.tospurfang.com/dt-management/activity/er.png" />
                    </Tooltip>
                  </vue-draggable-resizable>

                  <img class="disabledImage" ref="imgRef" :src="editorInfo.fileList[0]?.url" />
                </div>
                <div v-if="!editorInfo.fileList[0]?.url" class="noUrl">请先添加海报背景</div>
                <div class="erBoxCon" v-if="activeImgIndex == 1">
                  <div class="erbox" ref="erbox" v-if="hiddenFlag">
                    <div class="avatar">
                      <img src="https://static.tospurfang.com/dt-management/activity/tou.png" />
                    </div>

                    <div class="erText">
                      <p class="p1">
                        姓名
                        <span>手机号码</span>
                      </p>
                      <p class="p2">
                        <span>这里是项目地址，这里是项目地址</span>
                      </p>
                    </div>
                    <div class="erImg">
                      <img src="https://static.tospurfang.com/dt-management/activity/er.png" />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="qie">
            <div
              class="qieBox"
              v-for="(image, index) in imagesList"
              :key="index"
              :class="{ active: activeImgIndex === index + 1 }"
              @click="changeActive(index + 1)">
              <img :src="image.src" />
              <span>模板{{ index + 1 }}</span>
            </div>
          </div>
        </div>

        <div class="formBox">
          <Form ref="form" :model="editorInfo" :rules="rules" :label-width="140">
            <FormItem label="海报背景：" class="FormItemUpload" style="margin-top: 14px" prop="fileList">
              <div class="demo-upload-list" v-for="(item, index) in editorInfo.fileList" :key="index">
                <img :src="item.url" />
                <div class="demo-upload-list-cover">
                  <Icon type="ios-eye-outline" @click="handleView(item.url)"></Icon>
                  <Icon type="ios-trash-outline" @click="handleRemove(index)"></Icon>
                </div>
              </div>
              <Upload
                ref="upload"
                v-if="editorInfo.fileList.length > 0 ? false : true"
                :show-upload-list="false"
                :data="upload.data"
                :max-size="10240"
                name="multipartFile"
                :headers="upload.headers"
                :format="['jpg', 'png', 'jpeg']"
                type="drag"
                :on-format-error="handleFormatError"
                :before-upload="beforeUpload"
                :action="upload.reqUrl"
                style="display: inline-block; width: 58px">
                <div style="width: 58px; height: 58px; line-height: 58px">
                  <Icon type="ios-camera" size="20"></Icon>
                </div>
              </Upload>
              <span
                class="imageSize"
                v-if="editorInfo.fileList.length > 0 ? true : false"
                @click="agingUpload">
                重新裁剪
              </span>
              <span class="imageText" v-else>jpg、png、jpeg格式</span>
            </FormItem>
            <div class="addText">
              <Button type="primary" @click="addText">添加文案</Button>
              <p class="tips">
                <Icon type="md-alert" size="22" color="#2d8cf0" />
                该文案将出现在海报上面并且可自由拖动
              </p>
            </div>
            <FormItem label="文案：" style="margin-top: 14px">
              <div v-if="editorInfo.dragInfo.copyWriting?.length">
                <div class="textBox" v-for="(item, index) in editorInfo.dragInfo.copyWriting" :key="index">
                  <p>
                    <span>文案{{ index + 1 }}</span>
                    <span class="sp1" @click="delText(index)">删除</span>
                  </p>
                  <dt-editor
                    v-model="item.content"
                    :type="'toolbarList3'"
                    :maxLength="50"
                    :height="150"
                    @getEdit="getEdit"
                    @onEditorChange="
                      (e) => {
                        onEditorChange(e, item, index)
                      }
                    "></dt-editor>
                  <div class="wrong" v-if="item.sensitiveWords">敏感词汇： {{ item.sensitiveWords }}</div>
                </div>
              </div>
              <div v-else>暂无文案</div>
            </FormItem>
            <FormItem label="扫码落地页:">
              <span style="color: #999">（您可指定客户在海报中扫描二维码后所进入的页面）</span>
              <Select v-model="editorInfo.scanCodeType" disabled>
                <Option value="ONLINE_SALE_OFFICE">线上售楼处</Option>
              </Select>
            </FormItem>

            <FormItem label="朋友圈文案：" prop="wxContent">
              <div style="color: #999">（您可预先编辑朋友圈文案，以方便顾问在分享海报时快速复制）</div>
              <div class="wxText">
                <div style="width: 50%">
                  <Input
                    v-model="editorInfo.wxContent"
                    maxlength="500"
                    :autosize="{ minRows: 5 }"
                    show-word-limit
                    type="textarea"
                    placeholder="请输入微信文案..." />
                </div>
                <div class="wxTextVal">
                  <span>参考示例：</span>
                  <br />
                  🌊|同策壹号公馆 环湖首排正席|💎 🔥 | 6月18日 建档盛启 | 🔥 ———「 同策壹号 」——— 🏡约𝟵𝟵-𝟭𝟰𝟯㎡
                  | 湾心传世美宅 ✆888-88888 888宝藏地块 首开在即
                </div>
              </div>
            </FormItem>
          </Form>
        </div>
      </div>
      <div class="footer">
        <Button @click="addEditArticleReset" style="margin-left: 8px">取消</Button>
        <Button type="primary" @click="preViewScreen" style="margin-left: 8px">立即发布</Button>
      </div>
    </div>
    <dt-cropper ref="dtCropper" @success="getCropper" />
    <dt-loading :loading="loadingFlag"></dt-loading>

    <preview-image
      :images="preViewImg"
      :showDownLoad="showDownLoad"
      :showIndex="showIndex"
      :showBtn="showBtn"
      okText="立即发布"
      @prevImgEmit="prevImgEmit"
      @prevImgCancel="prevImgCancel"
      ref="preViewImage"></preview-image>
    <Modal v-model="leaveModal" title="离开" :footer-hide="true" :zIndex="99999">
      <p class="footer1Text">当前内容尚未保存，离开后将清空所填写的内容，是否要离开？</p>
      <div class="footer1">
        <Button @click="leave" style="margin-left: 8px">离开</Button>
        <Button type="primary" @click="leaveCancel" style="margin-left: 8px">暂不离开</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
  import toolMgr from '@/biz/base/tool.js'
  import bgMapMgr from '@/biz/bgMap/bgMap'
  import screenTemp from '@/components/screenTemp/screenTemp'
  import carousel from './components/carousel.vue'
  import domtoimage from 'dom-to-image'
  export default {
    components: {
      screenTemp,
      carousel
    },
    data() {
      return {
        lateFlag: false, //晚一会展示
        alwaysFlag: false,
        scaleVal: ['9:16', 'auto', 'no'],
        showBtn: true,
        loadingFlag: false,
        ratio: 1, // 你希望保持的宽高比
        imagesList: [
          { src: 'https://static.tospurfang.com/dt-management/activity/mu1.png' },
          { src: 'https://static.tospurfang.com/dt-management/activity/mu2.png' }
        ],
        activeImgIndex: 1,
        upload: toolMgr.unloadImage(),
        preViewImg: [],
        showIndex: 0,
        showDownLoad: false,
        editorInfo: {
          dragInfo: {
            copyWriting: []
          },
          qrCode: {
            coordinateX: 0,
            coordinateY: 100,
            height: 60,
            width: 60
            // url:''
          },
          fileList: [],
          scanCodeType: 'ONLINE_SALE_OFFICE',
          wxContent: ''
        },
        rules: {
          fileList: [{ required: true, message: '请上传图片', trigger: 'change' }]
        },
        imageHeight: 0,
        previewUrl: '',
        previewAppUrl: '',
        hiddenFlag: true,
        leaveModal: false,
        leveFlag: false,
        nextVal: '',
        editDom: ''
      }
    },
    methods: {
      getEdit(val) {
        this.editDom = val
        this.editDom.format('resize', '18px')
      },
      leaveCancel() {
        this.leaveModal = false
      },
      leave() {
        this.leaveModal = false
        this.leveFlag = true
        if (typeof this.nextVal === 'function') {
          this.nextVal()
        } else {
          this.$router.push({
            path: '/marketingCenter/shortArticle',
            query: { tabVal: '2' }
          })
        }
      },
      prevImgCancel() {},
      prevImgEmit(val) {
        this.imgWH = val
        this.loadingFlag = true
        this.downloadDomToImg(true).then((res) => {
          this.previewUrl = res
          this.hiddenFlag = false
          this.downloadDomToImg(true).then((res) => {
            this.previewAppUrl = res
            this.saveSc()
          })
        })
      },
      //预览后的保存
      saveSc() {
        let params = {
          buildingId: this.$dt.buildInfo().housesId,
          templateType: this.activeImgIndex, //海报模板
          picClipUrl: this.editorInfo.fileList[0]?.url,
          picUrl: this.editorInfo.fileList[0]?.url,
          dragInfo: this.editorInfo.dragInfo,
          scanCodeType: this.editorInfo.scanCodeType,
          wxContent: this.editorInfo.wxContent,
          previewWidth: this.imgWH.imageWidth,
          previewHeight: this.imgWH.imageHeight,
          previewUrl: this.previewUrl,
          previewAppUrl: this.previewAppUrl,
          qrCode: this.editorInfo.qrCode
        }
        if (this.$route.query.type == 'edit') {
          params.id = this.$route.query.id
          bgMapMgr
            .updateBuildingPoster(params)
            .then((res) => {
              if (res.sensitiveState == 1) {
                this.loadingFlag = false
                this.leave()
              } else {
                this.loadingFlag = false
                if (res.checkCopyWritings && res.checkCopyWritings.length) {
                  res.checkCopyWritings.forEach((item, index) => {
                    this.editorInfo.dragInfo.copyWriting[index].sensitiveWords = item.sensitiveWords
                  })
                }
                this.$Message.warning('请修改敏感词汇后提交')
              }
            })
            .catch((err) => {
              this.loadingFlag = false
              this.$Message.error(err)
            })
        } else {
          bgMapMgr
            .buildingPosterCreate(params)
            .then((res) => {
              if (res.sensitiveState == 1) {
                this.loadingFlag = false
                this.leave()
              } else {
                this.loadingFlag = false
                if (res.checkCopyWritings && res.checkCopyWritings.length) {
                  res.checkCopyWritings.forEach((item, index) => {
                    this.editorInfo.dragInfo.copyWriting[index].sensitiveWords = item.sensitiveWords
                  })
                }
                this.$Message.warning('请修改敏感词汇后提交')
              }
            })
            .catch((err) => {
              this.loadingFlag = false
              this.$Message.error(err)
            })
        }
      },
      downloadDomToImg(flag) {
        return new Promise((resolve, reject) => {
          this.$nextTick(() => {
            const ref = this.$refs.placardTem
            console.log(ref.scrollHeight, 'ref.scrollHeight')
            let that = this
            domtoimage
              .toPng(ref, {
                width: 750,
                height: ref.scrollHeight * 2,
                style: {
                  transform: 'scale(2)',
                  transformOrigin: 'left top'
                }
              })
              .then(function (dataUrl) {
                if (dataUrl) {
                  if (flag) {
                    let fileData = that.base64toFile(dataUrl)
                    resolve(that.unloadFileCanvas(fileData))
                  } else {
                    that.loadingFlag = false
                    that.preViewImg = []
                    that.preViewImg.push(dataUrl)
                    that.$refs.preViewImage.show()
                  }
                }
              })
              .catch(function (error) {
                console.error('生成失败', error)
                that.$emit('uploadSuccess', false)
                reject(error)
              })
          })
        })
      },
      unloadFileCanvas(image) {
        let params = {}
        params.multipartFile = image
        return bgMapMgr.unloadFileCanvas(params).then((res) => {
          return res.imageURL
        })
      },
      base64toFile(base, filename) {
        var arr = base.split(',')
        var mime = arr[0].match(/:(.*?);/)[1]
        var suffix = mime.split('/')[1]
        var bstr = atob(arr[1])
        var n = bstr.length
        var u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        //转换成file对象
        return new File([u8arr], `${filename}.${suffix}`, { type: mime })
      },

      // 立即发布展示预览
      preViewScreen() {
        this.alwaysFlag = true
        if (!this.editorInfo.fileList[0]?.url) {
          this.$Message.warning('请先上传海报背景')
          return false
        }
        this.showBtn = true
        this.loadingFlag = true
        setTimeout(() => {
          this.downloadDomToImg(false)
        }, 200)
      },
      onResize(x, y, width, height) {
        const newWidth = Math.round(height * this.ratio)
        const newHeight = Math.round(width / this.ratio)

        if (newWidth > width) {
          this.editorInfo.qrCode.width = newWidth
          this.editorInfo.qrCode.height = newWidth
        } else {
          this.editorInfo.qrCode.width = newHeight
          this.editorInfo.qrCode.height = newHeight
        }
      },
      changeActive(index) {
        this.alwaysFlag = false
        this.activeImgIndex = index
      },

      onDrag(x, y, item) {
        item.coordinateX = x
        item.coordinateY = y
      },
      // 二维码拖动
      onDragEr(x, y) {
        this.alwaysFlag = true
        this.editorInfo.qrCode.coordinateX = x
        this.editorInfo.qrCode.coordinateY = y
      },
      delText(index) {
        this.editorInfo.dragInfo.copyWriting.splice(index, 1)
      },
      addText() {
        if (this.editorInfo.contentList && this.editorInfo.contentList.length >= 5) {
          this.$Message.warning('最多只能添加五条文案')
        } else {
          this.editorInfo.dragInfo.copyWriting.push({
            content: '',
            contentText: '',
            coordinateX: 0,
            coordinateY: 0
          })
        }
      },
      onEditorChange(val, item) {
        item.contentText = val.text
        item.content = val.html
        if (val.html == '') {
          setTimeout(() => {
            this.editDom.format('resize', '18px')
          })
        }
      },
      agingUpload() {
        this.$refs.dtCropper.show({ file: this.oldFile, scaleVal: this.scaleVal })
      },
      getCropper(val) {
        console.log(val, 'vvvv')
        this.editorInfo.fileList = [
          {
            url: ''
          }
        ]
        this.lateFlag = false
        if (val) {
          let params = [
            {
              url: val,
              name: new Date().getTime()
            }
          ]
          this.editorInfo.fileList = params
          let img = new Image()
          img.src = val
          img.onload = () => {
            this.$nextTick(() => {
              this.imageHeight = this.$refs.imgRef.offsetHeight
              console.log(this.imageHeight, 'imageHeight')
              this.lateFlag = true
              setTimeout(() => {
                this.loadingFlag = false
              }, 100)
            })
          }
        }
      },
      addEditArticleReset() {
        this.leaveModal = true
      },
      handleFormatError(file) {
        this.$Message.warning('图片格式只支持jpg,png格式！')
      },
      beforeUpload(file) {
        const isJpg = file.type === 'image/jpeg'
        const isPng = file.type === 'image/png'
        const isLt2M = file.size / 1024 / 1024 < 10

        if (!isJpg && !isPng) {
          this.$Message.error('只能上传 JPG 或 PNG 格式的图片')
          return false
        }

        if (!isLt2M) {
          this.$Message.error('图片大小不能超过 10MB')
          return false
        }

        this.oldFile = file
        this.$refs.dtCropper.show({ file: this.oldFile, scaleVal: this.scaleVal })
        return false
      },
      handleView(val) {
        this.showBtn = false
        this.preViewImg = [val]
        this.$refs.preViewImage.show()
      },
      handleRemove(index) {
        this.editorInfo.fileList.splice(index, 1)
      }
    },
    beforeRouteLeave(to, from, next) {
      if (this.leveFlag) {
        next()
      } else {
        this.leaveModal = true
        this.nextVal = next
      }
    },
    created() {
      if (this.$route.query.type == 'add') {
      } else if (this.$route.query.type == 'edit') {
        bgMapMgr
          .getBuildingPosterById({ posterId: this.$route.query.id })
          .then((res) => {
            if (res) {
              let img = new Image()
              img.src = res.picClipUrl
              img.onload = () => {
                this.$nextTick(() => {
                  this.imageHeight = this.$refs.imgRef.offsetHeight
                  this.lateFlag = true
                })
              }
              this.activeImgIndex = res.templateType
              this.editorInfo.fileList = res.picClipUrl ? [{ url: res.picClipUrl }] : []
              this.editorInfo.dragInfo = JSON.parse(res.dragInfo)
              this.editorInfo.scanCodeType = res.scanCodeType
              this.editorInfo.wxContent = res.wxContent
              this.editorInfo.scanCodeType = res.scanCodeType
              this.editorInfo.qrCode = JSON.parse(res.qrCode)
            }
          })
          .catch((err) => {
            this.$Message.error(err, '111')
          })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .disabledImage {
    user-select: none;
    pointer-events: none; /* 禁用鼠标事件 */
    display: block;
    width: 100%;
  }
  .addEditArticlePageCont {
    word-wrap: break-word;
    overflow: hidden;
    .addEditArticlePageMian {
      margin-top: 16px;
      height: calc(100% - 60px);
      position: relative;
      .allBox {
        display: flex;
        flex-direction: row;
        padding: 0 10px;
        height: 100%;
        .tempPe {
          width: 40%;
          border: 1px #ccc solid;
          padding: 10px;
          .tit {
            font-size: 20px;
            font-weight: bold;
            span {
              color: #ff9900;
              font-size: 14px;
              margin-left: 20%;
              font-weight: normal;
            }
          }
          .titX {
            background-color: #c1e0ff;
            padding: 5px 10px;
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            span:last-child {
              color: #0080ff;
              cursor: pointer;
            }
          }
        }
        .formBox {
          overflow-y: scroll;
          height: 100%;
          width: 60%;
          padding: 10px 20px;
          border: 1px #ccc solid;
          margin-left: 5px;
        }
      }
    }
    .ivu-form-item {
      margin-bottom: 10px;
    }
    .check1 {
      height: 40px;
      padding-left: 130px;
      color: #ed4014;
    }
  }
  .footer {
    margin-top: 5px;
    text-align: center;

    button {
      margin: 0 10px;
    }
  }

  .footer1Text {
    padding: 20px 0;
  }
  .footer1 {
    text-align: center;
    margin: 20px 0;
    button {
      margin: 0 10px;
    }
  }
  .demo-upload-list {
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
    margin-right: 4px;
  }

  .demo-upload-list img {
    width: 100%;
    height: 100%;
  }

  .demo-upload-list-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.6);
  }
  .demo-upload-list:hover .demo-upload-list-cover {
    display: block;
  }
  .demo-upload-list-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }

  .FormItemUpload .ivu-form-item-content {
    display: flex;
  }
  .imageSize {
    display: inline-block;
    margin-left: 16px;
    vertical-align: top;
    padding-top: 16px;
    font-size: 12px;
    color: #2d8cf0;
    cursor: pointer;
  }
  .imageText {
    display: inline-block;
    margin-left: 16px;
    vertical-align: top;
    padding-top: 16px;
    font-size: 12px;
    color: #999;
  }
  .wxTextVal {
    flex: 1;
    background-color: #eee;
    border: 1px #ccc solid;
    padding: 5px;
    margin-left: 5px;
    line-height: 1.5;
  }
  .wrong {
    color: red;
  }
  .min {
    display: block;
  }
  .wxText {
    display: flex;
    flex-direction: row;
  }
  .placardTemBox {
    height: calc(100% - 150px);
    overflow-x: hidden;
    overflow-y: auto;
    // scrollbar-width: none;
    // width: 375px;
    margin: 10px auto 0;
  }
  .placardBox {
    height: 100%;
    width: 375px;
    margin: 0 auto;
  }
  .placardTem {
    width: 375px;
    box-sizing: border-box;
    background: #fff;
    .noUrl {
      min-height: 400px;
      font-size: 20px;
      font-weight: bold;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .tips {
    padding: 5px 10px;
    background-color: #fefcec;
    font-size: 14px;
  }
  .addText {
    margin-top: 30px;
    padding-left: 140px;
    display: flex;
    flex-direction: row;
  }
  .textBox {
    p {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      .sp1 {
        cursor: pointer;
        color: #0080ff;
      }
    }
  }
  .qie {
    height: 106px;
    width: 200px;
    margin: 10px auto 0;
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    .qieBox {
      height: 106px;
      border: 2px transparent solid;
      text-align: center;
      img {
        max-width: 100%;
        height: 80px;
        display: block;
        cursor: pointer;
      }
    }
    .qieBox.active {
      border: 2px #2d8cf0 solid;
    }
  }
  .erBoxCon {
    height: 106px;
  }
  .erbox {
    width: 100%;
    padding: 16px;
    user-select: none;
    pointer-events: none;
    display: flex;
    flex-direction: row;
    .avatar {
      img {
        display: block;
        width: 40px;
        height: 40px;
        border-radius: 50%;
      }
    }
    .erText {
      margin-left: 12px;
      padding-right: 16px;
      flex: 1;
      .p1 {
        font-size: 16px;
        font-weight: bold;
        line-height: 18px;
        margin-top: 10px;
        span {
          font-weight: normal;
        }
      }
      .p2 {
        font-size: 14px;
        margin-top: 4px;
        color: #999;
      }
    }
    .erImg {
      width: 100px;
      padding-left: 20px;
      position: relative;
      z-index: 1;

      img {
        display: block;
        width: 64px;
        height: 64px;
        border-radius: 50%;
      }
    }
  }
  .vdr {
    touch-action: none;
    border: none;
  }
  .toolName {
    width: 70px !important;
  }
</style>
